package com.xipu.yygh.controller;

import com.xipu.yygh.common.result.R;
import com.xipu.yygh.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * description: 第三方短信服务接口
 * @author: gql
 * @date: 2022/05
 */
@RequestMapping("/api/sms")
@RestController
public class SmsController {

    /**
     * 短信服务
     */
    @Autowired
    private SmsService smsService;

    /**
     * RedisTemplate
     */
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 1.发送短信
     * @param phone 手机号
     * @return R
     */
    @GetMapping(value = "/send/{phone}")
    public R sendMessage(@PathVariable String phone) {
        // 1.60s内仅发送1次
        if (StringUtils.isEmpty(this.redisTemplate.opsForValue().get(phone))) {
            String code = new DecimalFormat("0000").format(new Random().nextInt(10000));
            boolean flag;
            try {
                flag = this.smsService.sendMessage(phone, code);
            } catch (Exception e) {
                return R.error();
            }
            if (flag) {
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
                return R.ok();
            } else {
                return R.error();
            }
        } else {
            return R.ok();
        }
    }
}
